package cn.jdy.dzdd.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.service.UserColumnService;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.dzdd.entity.DzddNews;
import cn.jdy.dzdd.service.DzddNewsService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.platform.entity.ConfValue;

/**
 * @desc 投稿控制类
 * @author nignqian
 * @date   2016-10-26
 */
@Controller
@RequestMapping("/dzddarticle")
public class DzddArticleCtrl extends BaseCtrl {

	@Autowired
	private DzddNewsService newsService;
	@Autowired
	private UserColumnService userColumnService;
	//默认列表路径
	private static String viewName = "redirect:/dzddarticle/list?s=";

	/**
	 * 老河口公安分局
	 * 初始化,仅作页面跳转作用
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(DzddNews entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/articleList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		//mv.addObject("classList",  this.confService.djgajListColumn(GlobalConstant.TYPE_NEWS));
		User user = getUser();
		mv.addObject("userName", user.getUsername());
		//获取用户下的文章栏目id
		List<String> cIds = userColumnService.findUserColumn(user.getId());
		List<ConfValue> list = new ArrayList<ConfValue>();
		if(null != cIds && 0 < cIds.size()){
			for(String cid : cIds){
				ConfValue conf = new ConfValue();
				conf = confService.find(Long.valueOf(cid));
				list.add(conf);
			}
		}
		mv.addObject("classList", list);
		return mv;
	}
	
	/**
	 * 特警
	 * 初始化,仅作页面跳转作用
	 * @return
	 */
	@RequestMapping("/lists")
	public ModelAndView lists(DzddNews entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/articleLists.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "成功！");break;
				case '2': mv.addObject("msg", "删除成功！");break;
				case '3': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		return mv;
	}

	/**
	 * 老河口公安分局
	 * 异步查询
	 * 投稿文章状态为未审核
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(DzddNews news, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			news.setStatus("0");//未审核
			jsonMap.put("dataList", newsService.query1(news, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", newsService.count1(news, fromDate, toDate));
			jsonMap.put("iTotalRecords", newsService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}
	
	/**
	 * 老河口公安分局
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/articleDetail.jsp");
	//	mv.addObject("column", this.confService.queryByType(21, 0L));
		User user = getUser();
		mv.addObject("userName", user.getUsername());
		List<String> cIds = userColumnService.findUserColumn(user.getId());
		List<ConfValue> list1 = new ArrayList<ConfValue>();
		if(null != cIds && 0 < cIds.size()){
			for(String cid : cIds){
				ConfValue conf = new ConfValue();
				conf = confService.find(Long.valueOf(cid));
				list1.add(conf);
			}
		}
		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));
		mv.addObject("column1", confService.findConfValueByPid(10242L));
		mv.addObject("ctime", DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		mv.addObject("column", list1);
		DzddNews news = this.newsService.find(id);
		if(id!=null){
		mv.addObject("data", news);
		mv.addObject("ctime", DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		}
		// 获得系统所有签收单位
		List<ConfValue> list = confService.queryByType(72,null);
		mv.addObject("deptList", list);
		
		DzddNews datas = this.newsService.find(id);
		DzddNews datanewsNews = new DzddNews();
		mv.addObject("data", id==null||id==0 ? datanewsNews : datas);
		//User user = getUser();
		//mv.addObject("username", user.getUsername());
		return mv;
	}

	/**
	 * 老河口公安分局
	 * 保存（更新）投稿
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(DzddNews news, Long pid) {
		ModelAndView mv = new ModelAndView();
		try {
			//如果二级新闻类别为空，则使用一级类别
      if(null == news.getColumnId()) {
        news.setColumnId(pid);
      }
	      String names = news.getDepartment();
	      if(names.equals("")){
	    	  User user = getUser();
	    	  news.setUserid(user.getId());
	    	  names = user.getUsername();
	      }
	      news.setUsername(names);
			if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
				news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
			}//老河口公安分局
			 if(news.getId()==null) {// 新增文章
					//
					news.setDepartment(news.getUsername());
					news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
					this.newsService.save(news);
					mv.setViewName(this.viewName.concat("1"));
					}else{
		//更新文章
//			news.setCreateTime(news.getCreateTime());//老河口公安分局
			this.newsService.update(news);
			mv.setViewName(this.viewName.concat("2"));
	    // 清理文章缓存
	    NginxPurgeCacheUtil.purge(2, news.getId());
	    }
		// 清理栏目列表缓存
		NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "稿件保存异常！", e);
		}

		return mv;
	}
	/**
	 * 老河口公安分局
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.newsService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
            NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}
	

}
